<template>
  <div>
    <h3 style="text-align: center">商品列表</h3>
    <!--  查询表单-->
    <el-form :inline="true" :model="productObj" class="demo-form-inline">
      <el-form-item label="商品名称">
        <el-input v-model="productObj.search_name" placeholder="商品名称"></el-input>
      </el-form-item>
      <el-form-item label="商品类型">
        <div class="block">
          <el-cascader
              v-model="productObj.search_typeId"
              :options="typeOptions"
              @change="handleChange"></el-cascader>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search">查询</el-button>
      </el-form-item>
    </el-form>

    <el-table
        :data="productAry"
        style="width: 100%">
      <el-table-column
          prop="productId"
          label="商品id"
          width="100">
      </el-table-column>
      <el-table-column
          prop="name"
          label="商品名称"
          width="150">
      </el-table-column>
      <el-table-column
          prop="typeId"
          label="商品类型"
          width="100">
      </el-table-column>
      <el-table-column
          prop="imgLink"
          label="商品图片"
          width="200">
      </el-table-column>
<!--      <el-table-column-->
<!--          prop="stock"-->
<!--          label="上架库存"-->
<!--          width="150">-->
<!--      </el-table-column>-->

      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
              size="mini"
              type="success"
              @click="purchaseById(scope.row.productId)"
          >采购</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
        title="供应商名单"
        :visible.sync="dialogVisible"
        width="30%">
      <el-table
          :data="purchaseAry"
          style="width: 100%">
        <el-table-column
            prop="companyName"
            label="供应商名称"
            width="100">
        </el-table-column>
        <el-table-column
            prop="supplierProduct.price"
            label="商品价格(元)"
            width="150">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
                size="mini"
                type="warning"
                @click="addProduct(scope.row.supplierProduct.id)"
            >选择</el-button>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button  @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>

    <!--  分页工具-->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="pageSizes"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>
    <hr>
    <H3 style="text-align: center">采购计划单</H3>
    <form style="text-align: right">
      <el-button type="warning" @click="previewPur">预览</el-button>
      <el-button type="success" @click="addPurchase">确认</el-button>
    </form>
    <el-form :inline="true" :model="purchaseObj" class="demo-form-inline">
      <el-form-item label="登记人">
        <el-input v-model="purchaseObj.register" placeholder="登记人"></el-input>
      </el-form-item>
      <el-form-item label="登记人">
        <el-date-picker
            v-model="purchaseObj.registerTime"
            type="datetime"
            placeholder="选择日期"
            value-format="yyyy-MM-dd HH:mm:ss">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="支付方式">
        <el-select v-model="purchaseObj.payMethod" placeholder="支付方式">
          <el-option label="余额支付" value="P002-1"></el-option>
          <el-option label="微信支付" value="P002-2"></el-option>
          <el-option label="现金支付" value="P003"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <el-table
        :data="purchaseObj"
        style="width: 100%">
      <el-table-column
          prop="product.name"
          label="商品名称"
          width="150">
      </el-table-column>
      <el-table-column
          prop="supplier.companyName"
          label="供应商名称"
          width="150">
      </el-table-column>
      <el-table-column
          prop="supplierProducts.price"
          label="价格"
          width="150">
      </el-table-column>
      <el-table-column
          prop="count"
          label="数量"
          width="300">
        <template slot-scope="scope">
          <el-input v-model="scope.row.count"></el-input>
        </template>
      </el-table-column>
<!--      <el-table-column-->

<!--          label="总价"-->
<!--          width="150">-->
<!--        <template slot-scope="scope">-->
<!--          <p>{{ scope.row.subtotal }}</p>-->
<!--        </template>-->
<!--      </el-table-column>-->
    </el-table>

  </div>
</template>

<script>
export default {
  data() {
    return {
      //当前页号
      currentPage: 1,
      //总记录数
      total: 0,
      //当前页大小
      pageSize: 5,
      //页大小列表
      pageSizes: [2, 5, 10, 20],
      //查询条件
      productObj: {},
      //商品数组
      productAry: [],
      //供应商数组
      purchaseAry: [],
      //供应商面板默认隐藏
      dialogVisible : false,
      //采购明细
      purchaseObj:[],
      purchaseDetails:{},
      purchaseOrderObj:[],
      //定义一个从后端查询数据的级联选项
      typeOptions : []

    }
  },
  methods:{
    //查询级联数据,商品类型表
    async fetchCascaderOptions(){
      const {data:res}=
          await this.$http.post(`/community/productType/list`)
      const typeOptions = []; // 初始化级联选项数组
      const map = {}; // 用于快速查找的映射
      // 遍历所有商品类型并构建映射
      res.forEach(item => {
        map[item.typeId] = { value: item.typeId,label: item.typeName, children: [] }; // 复制对象并添加 children 属性
      });
      // 遍历所有商品类型，并为其添加 children
      res.forEach(item => {
        if (item.parentId === null) {
          // 顶级商品类型，直接添加到 typeOptions
          typeOptions.push(map[item.typeId]);
        } else {
          // 子级商品类型，添加到其父级的 children 数组中
          map[item.parentId].children.push({value: item.typeId,label: item.typeName,});
        }
      });
      // 将最终的级联选项数组赋值给组件的 data 属性
      this.typeOptions = typeOptions;
      // console.log(this.typeOptions)
    },
    //查询商品
    async getProduct(){
      if (this.productObj.search_typeId!=null){
        const search_typeId=this.productObj.search_typeId.join('-')
        // console.log(search_typeId)
        this.productObj.search_typeId=search_typeId
      }
      // console.log(this.productObj)
      //发送异步请求的post方法
      //带条件分页查询所有已上架的商品
      const {data:res}=
          await this.$http.post(`/community/product/queryOnOff?pageNo=`+this.currentPage+`&pageSize=`+this.pageSize,this.productObj)
      // console.log(res)
      this.productAry = res.rows
      this.total = res.total
    },
    handleChange() {
      console.log(this.productObj);
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.getProduct()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.getProduct()
    },
    search(){
      this.pageNo=1
      this.getProduct()
    },
    //商品的对应供应商列表
    async purchaseById(productId){
      this.dialogVisible=true;
      const {data:res}=
          await this.$http.post(`/community/supplierProduct/purchaseById?productId=`+productId)
      // console.log(res)
      this.purchaseAry=res
      // console.log(this.purchaseAry)
    },
    //添加采购商品
    async addProduct(id){
      // console.log(id)
      const {data:res}=
          await this.$http.post(`/community/supplierProduct/addProduct?id=`+id)
      console.log(res)
      const pObj=res[0]

      let index = -1;
      for (let i=0; i<this.purchaseObj.length; i++) {
        if (this.purchaseObj[i].product.productId==pObj.product.productId
            &&this.purchaseObj[i].supplier.supplierId==pObj.supplier.supplierId){
            index = i
          break
        }
      }
      if (index==-1){
        //将该对象添入数组中
        this.purchaseObj.push(pObj)
      }
    },
    //预览采购的商品,并计算价格
    previewPur(){
      // console.log(this.purchaseObj)
      // const number = parseInt(this.purchaseObj[0].count)
      // console.log(this.purchaseObj[0].count)
      for (let i=0; i<this.purchaseObj.length; i++) {
        //将字符串类型count转换为int类型
        const number = parseInt(this.purchaseObj[i].count)
        // console.log(number)
        //计算该商品的价格,单价*数量
        const total = this.purchaseObj[i].supplierProducts.price * number
        // console.log(total)
        //将单个商品需要的总价赋值给数组中对应的字段
        this.purchaseObj[i].subtotal = total
        // console.log(this.purchaseObj[i])

      }
      // console.log(this.purchaseObj)
    },
    //确认采购的商品,并制定对应的采购单和采购明细
    async addPurchase(){
      // console.log(this.purchaseObj)
      // const {data:res}=
      //     await this.$http.post(`/community/purchaseOrder/addPurchase`,this.purchaseObj)
      for (let i=0; i<this.purchaseObj.length; i++) {
        this.purchaseDetails={}
        //设置采购明细表的商品id
        this.purchaseDetails.productId = this.purchaseObj[i].supplierProducts.productId
        //设置采购明细表的采购数量
        this.purchaseDetails.count = parseInt(this.purchaseObj[i].count)
        //设置商品的单价
        this.purchaseDetails.price = this.purchaseObj[i].supplierProducts.price
        //设置该商品采购需要的总价
        this.purchaseDetails.subtotal = this.purchaseObj[i].subtotal
        //设置供应商id
        this.purchaseDetails.supplierId = this.purchaseObj[i].supplierProducts.supplierId
        // console.log(this.purchaseDetails)
        this.purchaseOrderObj.push(this.purchaseDetails)
      }
      const date=this.purchaseObj.registerTime
      for (let i=0; i<this.purchaseOrderObj.length; i++){
        //登记人
        this.purchaseOrderObj[i].register=this.purchaseObj.register
        //登记人时间
        this.purchaseOrderObj[i].registerTime=date
        //支付方式
        this.purchaseOrderObj[i].payMethod=this.purchaseObj.payMethod
      }
      // console.log(this.purchaseOrderObj)
      //添加采购单与采购明细单
      const {data:res}=
          await this.$http.post(`/community/purchaseOrder/addPurchase`,this.purchaseOrderObj)
      this.purchaseOrderObj = []
      // console.log(this.purchaseOrderObj)
      this.purchaseObj = []
      this.getProduct()
      alert("采购成功")
    }

  },
  mounted() {
    this.fetchCascaderOptions()
  }
}
</script>

<style scoped>

</style>